<?php

// $Id: site_web_page_wed_ua.class.php 1571 2009-01-13 13:08:33Z ogrebg $

require_once(TANGRA_MAIN_DIR.'web_site/redirect_composer_local.class.php');
require_once(TANGRA_MAIN_DIR.'web_site/web_page/just_headers_view.class.php');


require_once('site_web_page_wed.class.php');


abstract class Site_Web_Page_WED_UA extends Site_Web_Page_WED {
	protected $user;
	private $ua_config;
	private $use_return_to;	
	

	function __construct($page_name, $ua_config, $use_return_to = true) {
		parent::__construct($page_name);

		$this->use_return_to = $use_return_to;		
		$this->set_ua_config($ua_config);
	}


	public function set_ua_config($ua_config) {
		$this->ua_config = $ua_config;
	}


	public function get_ua_config() {
		return $this->ua_config;
	}


	public function _run() {
		$user_auth_config = $this->get_ua_config();

		$svm = $this->get_svm();
		if ($svm->is_global_var_registered($user_auth_config['session_var_name'])) {
			$user = $svm->get_global_var($user_auth_config['session_var_name']);

			if ($user instanceof User) {
				$this->user = $user;
				$this->export('_username', $user->get_username());
				$ret = parent::_run();
			} else {
				// Something is wrong. $user is not instance of User so go to login
				$ret = $this->redirect();
			}
		} else {
			$ret = $this->redirect();
		}

		return $ret;
	}




	private function redirect() {
		$user_auth_config = $this->get_ua_config();

		$redir_composer = new Redirect_Composer_Local($this->get__context(), $user_auth_config['login_page']);

		$context = $this->get__context();
		if ($this->get_use_return_to()) {		
			// if POST is not empty is not safe to send returnto, because with session expired we can not
			// validate the form submission (form_guard will not know guard pairs and thus will lead to
			// additional exceptions (Form protection failure))
			$post = $context->query_var('POST');
	
			if (!$post) {
				$params_raw = $context->get_from_server('QUERY_STRING');
				$params = urlencode($params_raw);
	
				$redir_composer->add_param_pair($user_auth_config['returnto'], $this->get_page_url_name());
				$redir_composer->add_param_pair($user_auth_config['returntoparams'], $params);
			}
		}

		$redir_view = new Just_Headers_View();
		$redir_view->add_http_header($redir_composer->get_location($context));


		return $redir_view;
	}


	public function get_user() {
		return $this->user;
	}
	
	
	public function get_use_return_to() {
		return $this->use_return_to;
	}	
	
}